package com.haitaoit.chengquan.module.home.activity.fabu;

import android.app.ActionBar;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.QBaseActivity;
import com.haitaoit.chengquan.module.center.model.ProvinceBase;
import com.haitaoit.chengquan.module.center.model.area;
import com.haitaoit.chengquan.module.center.model.city;
import com.haitaoit.chengquan.module.home.adapter.forum.ImageAdapter;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetPhotoListener;
import com.haitaoit.chengquan.utils.GetPhotoOrImage;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.haitaoit.chengquan.view.pickerview.TimePopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class QSendNeedActivity extends QBaseActivity {
    @ViewInject(R.id.need_type_tv)
    TextView need_type_tv;
    @ViewInject(R.id.send_view1)
    LinearLayout send_view1;
    @ViewInject(R.id.send_view2)
    LinearLayout send_view2;
    @ViewInject(R.id.send_view3)
    LinearLayout send_view3;
    @ViewInject(R.id.send_view4)
    LinearLayout send_view4;
    @ViewInject(R.id.send_view5)
    LinearLayout send_view5;
    @ViewInject(R.id.send_view6)
    LinearLayout send_view6;
    @ViewInject(R.id.send_view7)
    LinearLayout send_view7;
    @ViewInject(R.id.need_time_tv)
    TextView need_time_tv;
    @ViewInject(R.id.need_title)
    EditText need_title;
    @ViewInject(R.id.need_describe)
    EditText need_describe;
    @ViewInject(R.id.need_price)
    EditText need_price;
    @ViewInject(R.id.need_address)
    EditText need_address;
    @ViewInject(R.id.need_peopel)
    EditText need_peopel;
    @ViewInject(R.id.need_gsname)
    EditText need_gsname;
    @ViewInject(R.id.need_lxrzw)
    EditText need_lxrzw;
    @ViewInject(R.id.need_phone)
    EditText need_phone;
    @ViewInject(R.id.sbwx_machine_brands)
    EditText sbwx_machine_brands;
    @ViewInject(R.id.sbwx_machine)
    EditText sbwx_machine;
    @ViewInject(R.id.sbwx_numerical_control_system)
    EditText sbwx_numerical_control_system;
    @ViewInject(R.id.sbwx_fixed_number_year)
    EditText sbwx_fixed_number_year;
    @ViewInject(R.id.jgdd_number_parts)
    EditText jgdd_number_parts;
    @ViewInject(R.id.jgdd_parts_material)
    EditText jgdd_parts_material;
    @ViewInject(R.id.jchc_consumable_name)
    EditText jchc_consumable_name;
    @ViewInject(R.id.jchc_material_brand)
    EditText jchc_material_brand;
    @ViewInject(R.id.jchc_specifications)
    EditText jchc_specifications;
    @ViewInject(R.id.jchc_material_number)
    EditText jchc_material_number;
    @ViewInject(R.id.jcpj_accessories_name)
    EditText jcpj_accessories_name;
    @ViewInject(R.id.jcpj_accessories_brand)
    EditText jcpj_accessories_brand;
    @ViewInject(R.id.jcpj_specifications)
    EditText jcpj_specifications;
    @ViewInject(R.id.jcpj_parts_number)
    EditText jcpj_parts_number;
    @ViewInject(R.id.jczl_group_project)
    EditText jczl_group_project;
    @ViewInject(R.id.jczl_group_number)
    EditText jczl_group_number;
    @ViewInject(R.id.jczl_group_brand)
    EditText jczl_group_brand;
    @ViewInject(R.id.jczl_specifications)
    EditText jczl_specifications;
    @ViewInject(R.id.jczl_machine)
    EditText jczl_machine;
    @ViewInject(R.id.jczl_system)
    EditText jczl_system;
    @ViewInject(R.id.jczl_numbe)
    EditText jczl_numbe;
    @ViewInject(R.id.eshsbmm_machine)
    EditText eshsbmm_machine;
    @ViewInject(R.id.eshsbmm_system)
    EditText eshsbmm_system;
    @ViewInject(R.id.eshsbmm_machine_brands)
    EditText eshsbmm_machine_brands;
    @ViewInject(R.id.eshsbmm_machine_generated_date)
    EditText eshsbmm_machine_generated_date;
    @ViewInject(R.id.eshsbmm_machine_number)
    EditText eshsbmm_machine_number;
    @ViewInject(R.id.eshsbgz_modified_content)
    EditText eshsbgz_modified_content;
    @ViewInject(R.id.eshsbgz_machine)
    EditText eshsbgz_machine;
    @ViewInject(R.id.eshsbgz_system)
    EditText eshsbgz_system;
    @ViewInject(R.id.eshsbgz_machine_brands)
    EditText eshsbgz_machine_brands;
    @ViewInject(R.id.eshsbgz_machine_production_date)
    EditText eshsbgz_machine_production_date;
    @ViewInject(R.id.eshsbgz_machine_number)
    EditText eshsbgz_machine_number;
    @ViewInject(R.id.title_img)
    ImageView title_img;
    @ViewInject(R.id.img_list)
    MyGridView img_list;
    @ViewInject(R.id.need_address_proven)
    TextView need_address_proven;
    @ViewInject(R.id.back)
    ImageView back;
    @ViewInject(R.id.title)
    TextView title;


    private int typeId = 0;
    private List<TitleModel> listType;

    private ImageAdapter adapter;
    private GetPhotoOrImage getPhotoOrImage;
    private int change = 0;

    private List<ProvinceBase> province;
    private List<city> city;
    private List<area> region;

    private ArrayList<String> options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();

    private String address_ctiy;
    private double latitude = 0;// 维度
    private double longitude = 0;// 经度
    private GeoCoder mSearch;

    private int pre_type_id;

    //    type:1需求商 2个人服务商 3企业服务商
    private String account_type;

    @Override
    public int getContentView() {
        return R.layout.activity_qsend_need;
    }

    @Override
    public void initView() {
        SDKInitializer.initialize(getApplicationContext());
//        setContentView_V(R.layout.activity_send_need);
        pre_type_id=getIntent().getIntExtra("type_id",0);

//        setLeftShow(1, R.mipmap.left);
//        backLeft_V();
        ViewUtils.inject(this);


        adapter = new ImageAdapter(this);
        adapter.setBackCall(backCall);
        img_list.setAdapter(adapter);
        getPhotoOrImage = new GetPhotoOrImage(this);

        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);
        setTitle(pre_type_id);
        account_type=PreferenceUtils.getPrefString("account_type", "");
        httpGetdemand_class_list();
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void updateUI(Message msg) {

    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        SDKInitializer.initialize(getApplicationContext());
//        setContentView_V(R.layout.activity_send_need);
//        pre_type_id=getIntent().getIntExtra("type_id",0);
//
////        setLeftShow(1, R.mipmap.left);
////        backLeft_V();
//        ViewUtils.inject(this);
//
//
//        adapter = new ImageAdapter(this);
//        adapter.setBackCall(backCall);
//        img_list.setAdapter(adapter);
//        getPhotoOrImage = new GetPhotoOrImage(this);
//
//        mSearch = GeoCoder.newInstance();
//        mSearch.setOnGetGeoCodeResultListener(listener);
//        setTitle(pre_type_id);
//        httpGetdemand_class_list();
//    }
//
//
    public void setTitle(int pre_typeId) {
        String str_type=null;
        switch (pre_typeId) {
            case 1:
                str_type= getString(R.string.qfacilitym_str_type_1);

                break;
            case 2:
                str_type= getString(R.string.qfacilitym_str_type_2);
                break;
            case 3:
                str_type= getString(R.string.qfacilitym_str_type_3);
                break;
            case 4:
                str_type= getString(R.string.qfacilitym_str_type_4);
                break;
            case 5:
                str_type= getString(R.string.qfacilitym_str_type_5);
                break;
            case 6:
                str_type= getString(R.string.qfacilitym_str_type_6);
                break;
            case 7:
                str_type= getString(R.string.qfacilitym_str_type_7);
                break;
        }
//        setTitle_V("发布需求" + "  "+str_type);
        title.setText("发布需求" + "  "+str_type);
        need_type_tv.setText(str_type);
        typeId=pre_typeId;
    }

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {//获取地址
                // 没有检索到结果
                ToastUtils.showToast("亲，您的地址是无效的，请重新填写哦！");
            } else {// 获取地理编码结果
                Log.e("tag", "result1:" + result.getAddress() + "====" + result.getLocation().latitude + "-----" + result.getLocation().longitude);
                latitude = result.getLocation().latitude;
                longitude = result.getLocation().longitude;
                // 发布
                httpadd_demand();
            }
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {// 获取经纬度
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            } else {// 获取反向地理编码结果
                Log.e("tag", "reverseGeoCodeResult1:" + reverseGeoCodeResult.toString());
            }
        }
    };

    @OnClick({R.id.back,R.id.title_img, R.id.need_time_tv, R.id.send_go, R.id.need_address_proven})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.title_img:
                Dialog dlg = DialogUtil.ShowPhotoDialog(this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 500);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.need_type_tv:// 需求分类
                SelectType();
                break;
            case R.id.need_time_tv:// 时间
                TimePopupWindow startTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
                startTime.setTime(new Date());// 时间选择后回调
                startTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        try {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date d1 = dateFormat.parse(getTime(date));
                            Date d2 = dateFormat.parse(dateFormat.format(new Date()));
                            if (d1.getTime() < d2.getTime()) {
                                ToastUtils.showToast("截止时间要大于当前时间！");
                            } else {
//                                long time = (d1.getTime() - d2.getTime());// 这样得到的差值是微秒级别
//                                int days = (int) (time / (24 * 60 * 60 * 1000));
//                                int hourNum = (int) (time / (60 * 60 * 1000) - days * 24);
                                need_time_tv.setText(getTime(date));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                startTime.showAtLocation(need_time_tv, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.need_address_proven://选择省市区
                options1Items = new ArrayList<String>();
                options2Items = new ArrayList<ArrayList<String>>();
                options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
                InputStream inputStream = getResources().openRawResource(R.raw.region);
                province(inputStream);
                // 地址选择器
                OptionsPopupWindow pwOptions = new OptionsPopupWindow(this, "选择地区");
                // 三级联动效果
                pwOptions.setPicker(options1Items, options2Items, options3Items, true);
                // 设置默认选中的三级项目
                pwOptions.setSelectOptions(0, 0, 0);
                // 监听确定选择按钮
                pwOptions.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        // 返回的分别是三个级别的选中位置
                        String tx = options1Items.get(options1) + ","
                                + options2Items.get(options1).get(option2) + ","
                                + options3Items.get(options1).get(option2).get(options3);
                        need_address_proven.setText(tx);
                        address_ctiy = options1Items.get(options1);
                    }
                });
                pwOptions.showAtLocation(LayoutInflater.from(this).inflate(R.layout.activity_my_address_add, null),
                        Gravity.BOTTOM, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                break;
            case R.id.send_go:// 发布
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                    if (typeId == 0) {
                        ToastUtils.showToast("请选择需求分类！");
                    } else if (need_title.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入需求标题！");
                    } else if (need_describe.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入详细描述！");
                    } else if (typeId == 1 && sbwx_machine_brands.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床品牌！");
                    } else if (typeId == 1 && sbwx_machine.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床型号！");
                    } else if (typeId == 1 && sbwx_numerical_control_system.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入数控系统型号！");
                    } else if (typeId == 1 && sbwx_fixed_number_year.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入设备使用年限！");
                    } else if (typeId == 5 && jgdd_number_parts.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入零件数量！");
                    } else if (typeId == 5 && jgdd_parts_material.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入零件材质！");
                    } else if (typeId == 3 && jchc_consumable_name.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入耗材名称！");
                    } else if (typeId == 3 && jchc_material_brand.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入耗材品牌！");
                    } else if (typeId == 3 && jchc_specifications.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入耗材规格型号！");
                    } else if (typeId == 3 && jchc_material_number.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入耗材数量！");
                    } else if (typeId == 4 && jcpj_accessories_name.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入配件名称！");
                    } else if (typeId == 4 && jcpj_accessories_brand.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入配件品牌！");
                    } else if (typeId == 4 && jcpj_specifications.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入配件规格型号！");
                    } else if (typeId == 4 && jcpj_parts_number.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入配件数量！");
                    } else if (typeId == 3 && jczl_group_project.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入组立项目！");
                    } else if (typeId == 3 && jczl_group_number.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床组立数量！");
                    } else if (typeId == 3 && jczl_group_brand.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入组立品牌！");
                    } else if (typeId == 3 && jczl_specifications.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入组立规格型号！");
                    } else if (typeId == 3 && jczl_machine.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床型号！");
                    } else if (typeId == 3 && jczl_system.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入系统型号！");
                    } else if (typeId == 3 && jczl_numbe.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入人数！");
                    } else if (typeId == 6 && eshsbmm_machine.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床型号！");
                    } else if (typeId == 6 && eshsbmm_system.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入系统型号！");
                    } else if (typeId == 6 && eshsbmm_machine_brands.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床品牌！");
                    } else if (typeId == 6 && eshsbmm_machine_generated_date.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床生产日期！");
                    } else if (typeId == 6 && eshsbmm_machine_number.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床数量！");
                    } else if (typeId == 7 && eshsbgz_modified_content.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入改造内容！");
                    } else if (typeId == 7 && eshsbgz_machine.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床型号！");
                    } else if (typeId == 7 && eshsbgz_system.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入系统型号！");
                    } else if (typeId == 7 && eshsbgz_machine_brands.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床品牌！");
                    } else if (typeId == 7 && eshsbgz_machine_production_date.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床生产日期！");
                    } else if (typeId == 7 && eshsbgz_machine_number.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入机床数量！");
                    } else if (need_time_tv.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择截止时间！");
                    } else if (need_price.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入参考价格！");
                    } else if (need_address_proven.getText().toString().equals("")) {
                        ToastUtils.showToast("请选择需求省市区地址！");
                    } else if (need_address.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入需求地点！");
                    } else if (need_peopel.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入联系人姓名！");
                    } else if (need_gsname.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入公司名称！");
                    } else if (need_lxrzw.getText().toString().equals("")) {
                        ToastUtils.showToast("请输入联系人职位！");
                    } else if (!Utils.isMobileNum(need_phone.getText().toString())) {
                        ToastUtils.showToast("手机号格式有误请重新输入！");
                    } else {
                        // 获取经纬度
                        mSearch.geocode(new GeoCodeOption().city(address_ctiy).address(need_address.getText().toString()));
                    }
                } else {
                    ToastUtils.showToast(getString(R.string.qSendNeed_service_can_puservice));
                }
                break;
        }
//        super.onClick(v);
    }

    // 发布需求
    private void httpadd_demand() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_demand + "user_id=" + PreferenceUtils.getPrefString("user_id", "")
                + "&sign=" + sign;

        JSONObject json = new JSONObject();
        try {
            json.put("type", typeId + "");
            json.put("title", need_title.getText().toString());
            json.put("describe", need_describe.getText().toString());
            json.put("offer_end_time", need_time_tv.getText().toString());
            json.put("reference_price", need_price.getText().toString());
            json.put("demand_site", (need_address_proven.getText().toString() + " " + need_address.getText().toString()));
            json.put("contact", need_peopel.getText().toString());
            json.put("company_name", need_gsname.getText().toString());
            json.put("contact_position", need_lxrzw.getText().toString());
            json.put("contact_phone", need_phone.getText().toString());
            json.put("latitude", latitude);
            json.put("longitude", longitude);
            /* 1 */
            json.put("sbwx_machine_brands", sbwx_machine_brands.getText().toString());
            json.put("sbwx_machine", sbwx_machine.getText().toString());
            json.put("sbwx_numerical_control_system", sbwx_numerical_control_system.getText().toString());
            json.put("sbwx_fixed_number_year", sbwx_fixed_number_year.getText().toString());
            /* 2 */
            json.put("jchc_consumable_name", jchc_consumable_name.getText().toString());
            json.put("jchc_material_brand", jchc_material_brand.getText().toString());
            json.put("jchc_specifications", jchc_specifications.getText().toString());
            json.put("jchc_material_number", jchc_material_number.getText().toString());
            /* 3 */
            json.put("jczl_group_project", jczl_group_project.getText().toString());
            json.put("jczl_group_number", jczl_group_number.getText().toString());
            json.put("jczl_group_brand", jczl_group_brand.getText().toString());
            json.put("jczl_specifications", jczl_specifications.getText().toString());
            json.put("jczl_machine", jczl_machine.getText().toString());
            json.put("jczl_system", jczl_system.getText().toString());
            json.put("jczl_numbe", jczl_numbe.getText().toString());
            /* 4 */
            json.put("jcpj_accessories_name", jcpj_accessories_name.getText().toString());
            json.put("jcpj_accessories_brand", jcpj_accessories_brand.getText().toString());
            json.put("jcpj_specifications", jcpj_specifications.getText().toString());
            json.put("jcpj_parts_number", jcpj_parts_number.getText().toString());
            /* 5 */
            json.put("jgdd_number_parts", jgdd_number_parts.getText().toString());
            json.put("jgdd_parts_material", jgdd_parts_material.getText().toString());
            /* 6 */
            json.put("eshsbmm_machine", eshsbmm_machine.getText().toString());
            json.put("eshsbmm_system", eshsbmm_system.getText().toString());
            json.put("eshsbmm_machine_brands", eshsbmm_machine_brands.getText().toString());
            json.put("eshsbmm_machine_generated_date", eshsbmm_machine_generated_date.getText().toString());
            json.put("eshsbmm_machine_number", eshsbmm_machine_number.getText().toString());
            /* 7 */
            json.put("eshsbgz_modified_content", eshsbgz_modified_content.getText().toString());
            json.put("eshsbgz_machine", eshsbgz_machine.getText().toString());
            json.put("eshsbgz_system", eshsbgz_system.getText().toString());
            json.put("eshsbgz_machine_brands", eshsbgz_machine_brands.getText().toString());
            json.put("eshsbgz_machine_production_date", eshsbgz_machine_production_date.getText().toString());
            json.put("eshsbgz_machine_number", eshsbgz_machine_number.getText().toString());

            JSONObject object = new JSONObject();
            object.put("img_url", file);
            json.put("title_img", object);
            JSONArray house_imgs = new JSONArray();
            for (int i = 0; i < adapter.getList().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("img_url", adapter.getList().get(i).getImg());
                house_imgs.put(jsonObject);
            }
            json.put("img_list", house_imgs);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, false, url, json, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            setResult(1);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 需求分类列表
    private void httpGetdemand_class_list() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdemand_class_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            listType = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void changeView() {
        if (typeId == 1) {
            send_view1.setVisibility(View.VISIBLE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 5) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.VISIBLE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 2) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.VISIBLE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 4) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.VISIBLE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 3) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.VISIBLE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 6) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.VISIBLE);
            send_view7.setVisibility(View.GONE);
        } else if (typeId == 7) {
            send_view1.setVisibility(View.GONE);
            send_view2.setVisibility(View.GONE);
            send_view3.setVisibility(View.GONE);
            send_view4.setVisibility(View.GONE);
            send_view5.setVisibility(View.GONE);
            send_view6.setVisibility(View.GONE);
            send_view7.setVisibility(View.VISIBLE);
        }
    }

    private void SelectType() {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < listType.size(); i++) {
            list.add(listType.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "");
        popSex.setPicker(list);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                need_type_tv.setText(listType.get(options1).getName());
                typeId = Integer.parseInt(listType.get(options1).getId());
                changeView();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(need_type_tv, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

    /**
     * 日期格式
     *
     * @param date
     * @return
     */
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.icon:
                    if (position == adapter.getList().size()) {
                        getPhotoOrImage.setGetPhotoListener(getPhoto1);
                        getPhotoOrImage.getImage();
                    } else {
                        Dialog dlg = DialogUtil.ShowTop(QSendNeedActivity.this, new BackCall() {
                            @Override
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.tv_photos:// 图库
                                        getPhotoOrImage.setGetPhotoListener(getPhoto);
                                        getPhotoOrImage.getImage();
                                        break;
                                    case R.id.tv_camera:
                                        List<Img> list = adapter.getList();
                                        list.remove(change);
                                        adapter.setList(list);
                                        adapter.notifyDataSetChanged();
                                        break;
                                }
                                super.deal(which, obj);
                            }
                        });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        QSendNeedActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.set(change, img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto1 = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.add(img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 记录文件名
    private String filename;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2) {
            if (data != null) {
                upbitmap = null;
                if (data.getExtras() != null && !("").equals(data.getExtras())) {
                    upbitmap = (Bitmap) data.getExtras().get("data");
                } else {
                    String str = data.getDataString();
                    if (str == null) {
                        return;
                    }
                    Uri uri = Uri.parse(str);
                    String path = GetAbserlutePath.getPath(this, uri);
                    if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                        upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                    } else {
                        ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                        return;
                    }
                }
                upbitmap = getSmallBitmap(upbitmap);
                file = bitmapToString(upbitmap);
                title_img.setImageBitmap(upbitmap);
            }
        } else {
            getPhotoOrImage.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * @param inputStream
     * @tab 解析从本地获取的json
     */
    private void province(InputStream inputStream) {
        String a = getString(inputStream);
        try {
            JSONObject jsondata = new JSONObject(a);
            Gson gson = new Gson();
            province = gson.fromJson(jsondata.getString("data"),
                    new TypeToken<List<ProvinceBase>>() {
                    }.getType());
//            Log.e("tag", province.toString());
            ArrayList<String> options2Items_i = null;
            ArrayList<ArrayList<String>> options3Items_j = null;
            for (int i = 0; i < province.size(); i++) {
                options1Items.add(province.get(i).getName());
                city = province.get(i).getCity();
                options2Items_i = new ArrayList<String>();
                options3Items_j = new ArrayList<ArrayList<String>>();
                for (int j = 0; j < city.size(); j++) {
                    options2Items_i.add(city.get(j).getName());
                    region = city.get(j).getArea();
                    ArrayList<String> options3Items_j_j2 = new ArrayList<String>();
                    for (int j2 = 0; j2 < region.size(); j2++) {
                        options3Items_j_j2.add(region.get(j2).getName());
                    }
                    options3Items_j.add(options3Items_j_j2);
                }
                options2Items.add(options2Items_i);
                options3Items.add(options3Items_j);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
